package io.gitee.zhangbinhub.acp.cloud.tools

import io.gitee.zhangbinhub.acp.boot.http.HttpHeaders
import io.gitee.zhangbinhub.acp.boot.tools.ServerTools
import io.gitee.zhangbinhub.acp.cloud.constant.AcpCloudConstant
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import org.noear.solon.Solon
import org.noear.solon.core.handle.Context

class CloudTools(private val serverTools: ServerTools) {
    fun getServerPort(): Int = serverTools.getServerPort()
    fun getServerIp(): String = serverTools.getServerIp()

    companion object {
        private fun includeHeader(headerName: String, includeAuthorization: Boolean) =
            (includeAuthorization && headerName.equals(HttpHeaders.AUTHORIZATION, true))
                    || headerName.startsWith(
                Solon.cfg().get(
                    AcpCloudConstant.TRANSMIT_HEADER_PROPERTIES_PREFIX,
                    AcpCloudConstant.TRANSMIT_HEADER_DEFAULT_PREFIX
                ), true
            )

        /**
         * 获取需要传递的Header
         * @param context 请求上下文
         * @param includeAuthorization 是否包含Authorization的传递，默认true
         */
        @JvmOverloads
        @JvmStatic
        fun transmitHeaders(
            context: Context? = null,
            includeAuthorization: Boolean = true
        ): MutableMap<String, String> =
            (context ?: Context.current())?.headerMap()?.filter { entity ->
                includeHeader(entity.key, includeAuthorization) && !CommonTools.isNullStr(entity.firstValue)
            }?.associate { entity ->
                Pair(entity.key, entity.firstValue)
            }?.toMutableMap() ?: mutableMapOf()
    }
}